package org.lql.algo.codecrush.week003;

import org.lql.algo.common.ListNode;

/**
 * @author: liangqinglong
 * @date: 2025-07-30 15:47
 * @description: 141. 环形链表 <a href="https://leetcode.cn/problems/linked-list-cycle/description/">...</a>
 **/
public class HasCycle {

    public boolean hasCycle(ListNode head) {
        // 边界判断：链表为空或只有一个节点，肯定没有环
        if (head == null || head.next == null) {
            return false;
        }

        // 初始化快慢指针
        ListNode slow = head;
        ListNode fast = head.next;

        // 遍历链表
        while (fast != null && fast.next != null) {
            // 快指针走两步，慢指针走一步
            if (fast == slow) {
                return true; // 相遇说明有环
            }
            slow = slow.next;
            fast = fast.next.next;
        }

        return false;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next = head.next.next;
        HasCycle hasCycle = new HasCycle();
        boolean result = hasCycle.hasCycle(head);
        System.out.println(result);
    }
}
